function refreshCaptcha() {
    var captchaImage = document.getElementById('captcha-image');
    captchaImage.src = '/refresh-captcha?' + new Date().getTime();
}

//提交更新操作
$('form[data-action="update"]').submit(function(event) {
    event.preventDefault();
    var form = $(this);
    var formData = form.serialize();
    var url = form.attr('action');
    
    // 显示加载状态
    const submitBtn = form.find('button[type="submit"]');
    const originalText = submitBtn.text();
    submitBtn.prop('disabled', true);
    submitBtn.text('处理中...');

    // 发送AJAX请求
    $.ajax({
        type: 'POST',
        url: url,
        data: formData,
        success: function(response) {
            if (response.success) {
                alert(response.message);
                window.location.href = '/home';
            } else {
                alert(response.message);
            }
        },
        error: function(xhr, status, error) {
            alert('请求出错：' + error);
        },
        complete: function() {
            // 恢复按钮状态
            submitBtn.prop('disabled', false);
            submitBtn.text(originalText);
        }
    });
});

// 处理登录表单提交
$('#loginForm').on('submit', function(e) {
    e.preventDefault();
    
    const $btn = $('.btn-login');
    const $spinner = $btn.find('.spinner-border');
    const $text = $btn.find('.login-text');
    
    $.ajax({
        type: 'POST',
        url: '/login',
        data: $(this).serialize(),
        beforeSend: function() {
            $btn.prop('disabled', true);
            $spinner.removeClass('d-none');
            $text.text('登录中...');
            $('.alert').hide();
        },
        success: function(response) {
            if (response.success) {
                $('.alert-success').text('登录成功，正在跳转...').fadeIn();
                setTimeout(() => window.location.href = '/home', 1000);
            } else {
                $('.alert-danger').text(response.message).fadeIn();
                refreshCaptcha();
            }
        },
        error: function() {
            $('.alert-danger').text('登录失败，请重试').fadeIn();
            refreshCaptcha();
        },
        complete: function() {
            $btn.prop('disabled', false);
            $spinner.addClass('d-none');
            $text.text('登录');
        }
    });
});